// registry  and  login
const { userService } = require("../Service/index");
const { idCreator } = require("../util/crypto");
const { query } = require("../util/mysql");
// 注册账号
const registry = async function (ctx) {
  const { username } = ctx.request.body;
  // 在数据库中查找 用户名是否存在
  const hasUser = await userService.getUserByName(username);

  if (hasUser.length) {
    return (ctx.body = { code: 0, msg: "用户名已存在" });
  }
  // 查不到则开始注册
  const result = await userService.registry({
    uid: idCreator(username),
    ...ctx.request.body,
  });
  if (result.affectedRows) {
    ctx.body = {
      code: 1,
      msg: "注册成功",
    };
  } else {
    ctx.body = {
      code: 0,
      msg: "注册失败",
    };
  }
};
// 登录
const login = async function (ctx) {
  const result = userService.login(ctx.request.body);
  if (result.affectedRows) {
    ctx.body = {
      code: 1,
      msg: "登录成功",
    };
  } else {
    ctx.body = {
      code: 0,
      msg: "登录失败",
    };
  }
};

const add = async function (ctx) {
  const { username } = ctx.request.body;
  const $sql = `select * from userinfo where username=?`;
  const pam = [username];
  const hasUser = await query($sql, pam);
  if (hasUser.length > 0) {
    ctx.body = {
      code: 0,
      msg: "此用户已经存在！",
    };
    return;
  }
  const result = await userService.add(ctx.request.body);

  console.log(result);
  if (result.affectedRows) {
    ctx.body = {
      code: 1,
      msg: "创建成功",
    };
    return;
  } else {
    ctx.body = {
      code: 0,
      msg: "创建失败",
    };
    return;
  }
};
const del = async function (ctx) {
  console.log(ctx);
  const result = await userService.del(ctx.request.body);
  if (result.affectedRows) {
    ctx.body = {
      code: 1,
      msg: "删除成功",
    };
    return;
  } else {
    ctx.body = {
      code: 0,
      msg: "删除失败",
    };
    return;
  }
};
const edit = async function (ctx) {
  console.log(ctx.request.body);
  const result = await userService.edit(ctx.request.body);
  console.log(result);
  if (result.affectedRows ==1) {
    ctx.body = {
      code: 1,
      msg: "编辑成功",
    };
    return;
  } else {
    ctx.body = {
      code: 0,
      msg: "编辑失败",
    };
    return;
  }
};
const gets = async function (ctx) {
  const result = await userService.gets();
  if (result.length) {
    ctx.body = {
      code: 1,
      msg: "请求成功",
      data: result,
    };
    return;
  } else {
    ctx.body = {
      code: 0,
      msg: "暂无数据",
    };
    return;
  }
};
module.exports.userController = {
  registry,
  login,
  add,
  del,
  edit,
  gets,
};
